package org.agora.photogallery.client.service;

import java.util.ArrayList;
import java.util.List;


import org.agora.photogallery.client.common.XmlUtils;
import org.agora.photogallery.client.model.Gallery;
import org.agora.photogallery.client.model.Photo;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.URL;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

public class PhotoServicePicasa implements PhotoService {
	 private static String GALLERY_URL = "http://picasaweb.google.com/data/feed/api/user/arashbi/albumid/";
	@Override
	public void getGalleries(final AsyncCallback<ArrayList<Gallery>> callback) {
		JsonpRequestBuilder jsonRequest = new JsonpRequestBuilder();
		 
        jsonRequest.requestString(URL.encode("http://picasaweb.google.com/data/feed/api/user/arashbi"), new AsyncCallback<String>() {
        
			@Override
			public void onSuccess(String result) {
				ArrayList<Gallery> galleries = new ArrayList<Gallery>();
				 digestXML(result, galleries);
				 callback.onSuccess(galleries);
				
            }

			@Override
			public void onFailure(Throwable caught) {
				GWT.log("Cold not fetch album list ", caught);
;				return;
			}
           });
    }


	@Override
	public  void getPhotoesFor(String galleryId, final AsyncCallback<ArrayList<Photo>> callback) {
	       JsonpRequestBuilder pr = new JsonpRequestBuilder();	        
	       final List<Photo> photos = new ArrayList<Photo>();
           pr.requestString(GALLERY_URL+galleryId, new AsyncCallback<String>() {
               @Override
               public void onFailure(Throwable caught) {
            	   GWT.log("Failed to get the photo list");
               }

               @Override
               public void onSuccess(String xml) {
            	   ArrayList<Photo> photoes = new ArrayList<Photo>();
            	   digestPhotoes(xml,photoes);
            	   callback.onSuccess(photoes);
                }

           });

        

   }
	
private void digestPhotoes(String xml, ArrayList<Photo> photoes) {
    Document doc = XMLParser.parse(xml);
    NodeList nodes = doc.getElementsByTagName("entry");
  
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        String url = XmlUtils.dig(node.getChildNodes(), "media:group", "media:content").getAttributes().getNamedItem("url").getNodeValue();
        Node desc = XmlUtils.dig(node.getChildNodes(), "media:group", "media:description").getFirstChild();
        GWT.log("description is " ,null);

        String description;
        if (node != null && desc ==null)
            description = "";
        else
            description = desc.toString().replaceAll("\n","<br/>");

        NodeList thumbs = XmlUtils.findAllByName(XmlUtils.findByName(node.getChildNodes(), "media:group").getChildNodes(), "media:thumbnail");
        Node t = thumbs.item(2);
        String thumbUrl = "";
        if (t != null) {
            thumbUrl = t.getAttributes().getNamedItem("url").getNodeValue();
        }
  
        Photo photo = new Photo(thumbUrl, url,description);
        System.out.println("Adding photo with url " + thumbUrl);
        photoes.add(photo);
    }

}	
	private void digestXML(String result, ArrayList<Gallery> galleries) {
        Document doc = XMLParser.parse(result);
        NodeList entries = doc.getElementsByTagName("entry");
        System.out.println("entries " + entries.getLength());
        for (int i = 0; i < entries.getLength(); i++) {
            String url;
            String title;
            Node node = entries.item(i);
            url = XmlUtils.dig(node.getChildNodes(), "media:group", "media:thumbnail").getAttributes().getNamedItem("url").getNodeValue();
            title = XmlUtils.dig(node.getChildNodes(), "title").getFirstChild().getNodeValue();
            String id = XmlUtils.dig(node.getChildNodes(), "gphoto:id").getFirstChild().getNodeValue();
            Gallery g = new Gallery(url,title, id);
            galleries.add(g);
            
        }
    }

}
